// import Vue from 'vue';
import { axios } from '@/utils/request';
import { message } from 'ant-design-vue';
import qs from 'qs';
import Vue from 'vue';
// import Vue from 'vue';
import router from '../router';
import { AESEncrypt } from '@/utils/utils';

const cid = 'NB6N66Eq3cshSi8DKxmc5W5Qkc4r7p3I';
const csid = 'AVe5dIGES3nhrXDl3ez65XoaQaw4KMCS';
const clientId = AESEncrypt(cid);
const clientSecret = AESEncrypt(csid);
const sign = AESEncrypt(`${cid}${csid}`);

export const SIGN = {
  clientId,
  clientSecret,
  sign
};

// import {
//   createFileUrl,
//   headersFormat,
//   getContentDispositionFilename
// } from '../utils/utils';

const setModal = (msg, showErr) => {
  if (showErr) message.error(msg);
};

/**
 * des: 封装请求
 * @param {String} url -接口地址
 * @param {String} parameter -请求入参
 * @param {Object} options -基础配置
 *    {
 *     contentType: 请求方式 默认 application/x-www-form-urlencoded 包含{json, urlencoded, formdata, text}
 *     method: 请求类型 默认 post
 *     baseURL: axios接口地址前缀，默认为 process.env.VUE_APP_SERVER_URL, 有需要自行配置
 *     AesKey: 传入AesKey 启用加密，加密请求头需与后端约定
 *     showErr: true or false, 请求异常显示提示弹框，默认true
 *    }
*/
const tokenKey = 'token-key'; // 加密请求头 与后端约定
function request(url, parameter, options, cb) {
  const formdata = {
    json: 'application/json',
    urlencoded: 'application/x-www-form-urlencoded',
    formdata: 'multipart/form-data',
    text: 'text/plain'
  };

  // 默认值
  const o = {
    method: 'post',
    baseURL: process.env.VUE_APP_USE_MOCK == true ? '/mock' : process.env.VUE_APP_SERVER_URL,
    contentType: 'urlencoded',
    data: qs.stringify(parameter),
    showErr: true,
    awalysSuccess: false,
    responseType: 'json',
    timeout: 120 * 1000,
    returnDefault: false
  };
  const obj = { ...o, ...options };
  const d = {
    url,
    method: obj.method,
    headers: {
      'Content-Type': formdata[obj.contentType],
      clientId,
      clientSecret,
      sign
    },
    responseType: obj.responseType,
    timeout: obj.timeout
  };
  if (obj.onUploadProgress) {
    d.onUploadProgress = obj.onUploadProgress;
  }
  if (obj.method === 'post' || obj.method === 'put' || obj.method === 'delete') {
    d.data = (obj.contentType === 'urlencoded') ? qs.stringify(parameter) : parameter;
  } else if (obj.method === 'get') {
    delete obj.data;
    d.params = parameter;
  }
  if (obj.baseURL) d.baseURL = obj.baseURL;
  if (obj.emptyBaseURL) d.baseURL = '';
  // 如果有加密
  if (obj.AesKey) d.headers[tokenKey] = obj.AesKey;

  return new Promise((resolve, reject) => {
    axios({
      ...d
    }).then((res) => {
      // console.log('axios got:', res);
      // const headers = headersFormat(res.headers);
      if (obj.returnDefault) {
        resolve(res);
        return;
      }
      res = res.data;
      if (obj.awalysSuccess) {
        resolve(res);
        return;
      }
      if (res.code === 0) {
        if (res.msg == '您的密码超过90天未做修改，现要求您强制更换新密码') {
          reject(res);
          return;
        }
        resolve(res);
      } else {
        setModal(res.message || res.errorMsg || res.msg, obj.showErr);
        if (res.code == '401') {
          Vue.ls.clear();
          Vue.ss.clear();
          router.push({ path: '/404', query: { error: res.message } });
        }
        reject(res);
      }
    }).catch((err) => {
      reject(err);
    });
  });
}

// urlencoded post 请求方式
export function post(url, parameter, obj) {
  return request(url, parameter, {
    ...obj
  });
}

// JSON post 请求方式
export function postJson(url, parameter, obj) {
  return request(url, parameter, {
    contentType: 'json',
    ...obj
  });
}

// put 请求方式
export function put(url, parameter, obj) {
  return request(url, parameter, {
    method: 'put',
    ...obj
  });
}

// put 请求方式
export function putJson(url, parameter, obj) {
  return request(url, parameter, {
    method: 'put',
    contentType: 'json',
    ...obj
  });
}

// get
export function get(url, parameter, obj) {
  return request(url, parameter, {
    method: 'get',
    ...obj
  });
}

// delete
export function deletes(url, parameter, obj) {
  return request(url, parameter, {
    contentType: 'urlencoded',
    method: 'delete',
    ...obj
  });
}

export function uploadFile(url, parameter, obj) {
  console.log(obj, 'obj');
  return request(url, parameter, {
    contentType: 'formdata',
    ...obj
  });
}

// 上传excel
export function uploadExcel(url, parameter, obj) {
  return request(url, parameter, {
    contentType: 'formdata',
    ...obj
  });
}
